package com.googlecode.tidej.client.util;

import com.google.gwt.core.client.JavaScriptObject;

public class Json {

  public static String quote(String s) {
    if (s == null) {
      return "null";
    }
    StringBuilder sb = new StringBuilder("'");
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      switch(c) {
      case '\'': 
        sb.append("\\'");
        break;
      default:
        sb.append(c < 32 ? ' ' : c);
      }
    }
    sb.append('\'');
    return sb.toString();
  }

  public static native JavaScriptObject parse(String serialized) /*-{
    return eval("(" + serialized + ")");
  }-*/;
  
  public static JavaScriptObject parseToObject(String serialized) {
    if (serialized == null || serialized.trim().toString().length() == 0) {
      return JavaScriptObject.createObject();
    }
    JavaScriptObject result = null;
    try {
      result = parse(serialized);
    } catch(Exception e) {
      result = JavaScriptObject.createObject();
    }
    return result;
  }

}
